<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefult">
        <el-select v-model="queryParams.isDefult" placeholder="请选择是否默认" clearable size="small">
          <el-option
            v-for="dict in isDefultOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="省名称" prop="provinceName">
        <el-input
          v-model="queryParams.provinceName"
          placeholder="请输入省名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="市名称" prop="cityName">
        <el-input
          v-model="queryParams.cityName"
          placeholder="请输入市名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区名称" prop="districtName">
        <el-input
          v-model="queryParams.districtName"
          placeholder="请输入区名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['userAddress:address:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['userAddress:address:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['userAddress:address:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['userAddress:address:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" border stripe :data="addressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="收货地址" align="center" prop="address" />
      <el-table-column label="是否默认" align="center" prop="isDefult" :formatter="isDefultFormat" />
      <el-table-column label="省名称" align="center" prop="provinceName" />
      <el-table-column label="市名称" align="center" prop="cityName" />
      <el-table-column label="区名称" align="center" prop="districtName" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['userAddress:address:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['userAddress:address:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户收货地址对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body center :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" placeholder="请输入用户ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="form.address" disabled="disabled" placeholder="请先 选择省市区 和 填写街道地址, 将自动生成 收货地址" />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-select v-model="form.isDefult" placeholder="请选择是否默认">
            <el-option
              v-for="dict in isDefultOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="省">
              <el-select v-model="form.province" size="small" @change="selectProvinceFun($event)" placeholder="请选择省份">
                <el-option v-for="dict in provinceOptions" :key="dict.id" :label="dict.regionName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市">
              <el-select v-model="form.city" size="small" @change="selectCityFun($event)" placeholder="请先选择 省份">
                <el-option v-for="dict in cityOptions" :key="dict.id" :label="dict.regionName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区">
              <el-select v-model="form.district" size="small" @change="selectAreaFun($event)" placeholder="请先选择 地市">
                <el-option v-for="dict in districtOptions" :key="dict.id" :label="dict.regionName" :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="街道地址" prop="street">
              <el-input v-model="form.street" @input="streetChange" placeholder="请填写街道地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAddress, getAddress, delAddress, addAddress, updateAddress, exportAddress } from "@/api/userAddress/address";
import { listRegion, listRegionAll } from "@/api/region/region";

export default {
  name: "Address",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户收货地址表格数据
      addressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 省
      provinceOptions: [],
      // 市
      cityOptions: [],
      // 区
      districtOptions: [],
      // 是否默认字典
      isDefultOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mobile: undefined,
        isDefult: undefined,
        provinceName: undefined,
        cityName: undefined,
        districtName: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [{
          required: false,
          message: '请填写用户ID',
          trigger: 'blur'
        }],
        mobile: [{
          required: false,
          message: '请填写手机号',
          trigger: 'blur'
        }]
      }
    };
  },
  created() {
    const that = this;
    this.getList();
    this.getDicts("is_active").then(response => {
      this.isDefultOptions = response.data;
    });
    that.getPID(function(pid) {
      if (pid) {
        that.getProvinceOptions(pid);
      }
    });
  },
  methods: {
    streetChange(s) {
      const that = this;
      that.form.street = s;
      that.form.address = (that.form.provinceName || '') + (that.form.cityName || '') + (that.form.districtName || '') + (that.form.street || '');
    },
    selectProvinceFun(pid) {
      const that = this;
      that.form.province = pid;
      that.form.city = '';
      that.form.cityName = '';
      that.form.district = '';
      that.form.districtName = '';
      that.getCityOptions(pid);
      that.provinceOptions.forEach(function(item){
        if (item.id == pid) {
          that.form.provinceName = item.regionName;
          that.form.address = (that.form.provinceName || '') + (that.form.cityName || '') + (that.form.districtName || '') + (that.form.street || '');
        }
      })
    },
    selectCityFun(cid) {
      const that = this;
      that.form.city = cid;
      that.form.district = '';
      that.form.districtName = '';
      that.getDistrictOptions(cid);
      that.cityOptions.forEach(function(item){
        if (item.id == cid) {
          that.form.cityName = item.regionName;
          that.form.address = (that.form.provinceName || '') + (that.form.cityName || '') + (that.form.districtName || '') + (that.form.street || '');
        }
      })
    },
    selectAreaFun(did) {
      const that = this;
      that.form.district = did;
      that.districtOptions.forEach(function(item){
        if (item.id == did) {
          that.form.districtName = item.regionName;
          that.form.address = (that.form.provinceName || '') + (that.form.cityName || '') + (that.form.districtName || '') + (that.form.street || '');
        }
      })
    },
    getPID(call) {
      const param = {
        pageNum: 1,
        pageSize: 1,
        parentId: '0'
      };
      listRegion(param).then(response => {
        const pid = response.rows[0].id || '';
        if (call) {
          call(pid);
        }
      });
    },
    getProvinceOptions(PID) {
      const that = this;
      listRegionAll({ parentId: PID }).then(response => {
        that.provinceOptions = response.data || [];
      });
    },
    getCityOptions(PID) {
      const that = this;
      listRegionAll({ parentId: PID }).then(response => {
        that.cityOptions = response.data || [];
      });
    },
    getDistrictOptions(CID) {
      const that = this;
      listRegionAll({ parentId: CID }).then(response => {
        that.districtOptions = response.data || [];
      });
    },
    /** 查询用户收货地址列表 */
    getList() {
      this.loading = true;
      listAddress(this.queryParams).then(response => {
        this.addressList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否默认字典翻译
    isDefultFormat(row, column) {
      return this.selectDictLabel(this.isDefultOptions, row.isDefult);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isActive: '1',
        lesseeId: '13',
        address: undefined,
        mobile: undefined,
        isDefult: '0',
        userId: undefined,
        userName: undefined,
        province: undefined,
        city: undefined,
        district: undefined,
        provinceName: undefined,
        cityName: undefined,
        districtName: undefined,
        street: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户收货地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const that = this;
      that.reset();
      const id = row.id || that.ids
      getAddress(id).then(response => {
        that.form = response.data;
        const myStr = (that.form.provinceName || '') + (that.form.cityName || '') + (that.form.districtName || '');
        if (that.form.address.indexOf(myStr) !== -1) {
          const list = that.form.address.split(myStr);
          that.form.street = list[1];
        } else {
          that.form.street = that.form.address;
        }
        that.getCityOptions(that.form.province);
        that.getDistrictOptions(that.form.city);
        that.open = true;
        that.title = "修改用户收货地址";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      const that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!that.form.userId) {
            that.$message({
              type: 'warning',
              message: '请填写用户ID'
            });
            return;
          }
          if (!that.form.mobile) {
            that.$message({
              type: 'warning',
              message: '请填写手机号'
            });
            return;
          } else {
            const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
            if (!reg.test(that.form.mobile)) {
              that.$message({
                type: 'warning',
                message: '请填写正确的手机号'
              });
              return;
            }
          }
          if (!that.form.provinceName) {
            that.$message({
              type: 'warning',
              message: '请选择省份'
            });
            return;
          }
          if (!that.form.cityName) {
            that.$message({
              type: 'warning',
              message: '请选择地市'
            });
            return;
          }
          if (!that.form.districtName) {
            that.$message({
              type: 'warning',
              message: '请选择区域'
            });
            return;
          }
          if (!that.form.street) {
            that.$message({
              type: 'warning',
              message: '请选择街道地址'
            });
            return;
          }
          if (this.form.id != undefined) {
            updateAddress(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAddress(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户收货地址编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAddress(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户收货地址数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAddress(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style>
  .el-dialog__footer .el-button+.el-button{
    margin-left: 30px;
  }
</style>
